    //
//  SleepViewController.m
//  SleepDetective
//
//  Created by Fei Hu on 12/12/10.
//  Copyright 2010 Southern Methodist University. All rights reserved.
//

#import "SleepDetectiveAppDelegate.h"
#import "SleepViewController.h"
#import "MMPDeepSleepPreventer.h"

#include <sqlite3.h>

@implementation SleepViewController

@synthesize label;
@synthesize lastAcceleration;
@synthesize deepSleepPreventer;
@synthesize goSleepBtn;
@synthesize imgStart,imgStop;
/* * * * * * * * * * * * * * * * * * * * *
 *
 *      START PROGRAMMING: FEI HU
 *
 * * * * * * * * * * * * * * * * * * * * */

int currentCycleID;
BOOL isStart;
// Detect shake motion
// Return BOOL
static BOOL IsDeviceShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
	
	//NSLog(@"--- ENter isShaking ---");
	double
	deltaX = fabs(last.x - current.x),
	deltaY = fabs(last.y - current.y),
	deltaZ = fabs(last.z - current.z);
	
	return
	(deltaX > threshold && deltaY > threshold) ||
	(deltaX > threshold && deltaZ > threshold) ||
	(deltaY > threshold && deltaZ > threshold);
}
// End of IsDeviceShaking

// Add the detected movement data to SQLite
// Format: timestamp
-(void) addMoveDataToDB {
	NSLog(@"--- INFO - START -> FUNCTION: addMOveToDB start ---");	
	
	// Open Database
	
	sqlite3 *db;
	int dbrc; //database RETURN CODE
	
	// create a singleton UIApplication object. Thereafter you can access this object by invoking the sharedApplicationclass method. 
	SleepDetectiveAppDelegate *appDelegate = (SleepDetectiveAppDelegate*)[UIApplication sharedApplication].delegate;
	
	const char* dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
	dbrc = sqlite3_open(dbFilePathUTF8, &db);
	if (dbrc) {
		NSLog(@"---ERROR - DB OPEN -> Couldn't Open DB! ---");
		return;
	} // End of Open DataBase
	NSLog(@"--- INFO - DB OPEN -> Open Database. ---");

	
	// INSERT TIMESTAMP
	// CERATE TABLE SQL:
	// CREATE  TABLE "main"."movement" ("ID" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "TIMESTAMP" DATETIME NOT NULL )
	// Add movement time to db
	sqlite3_stmt *dbps; //prepared statement
	// INSERT SQL: INSERT INTO move(TIMESTAMP, CYCLE) VALUES (DATETIME('now','localtime'), (SELECT MAX(CYCLE)+1 FROM move));
	NSString *insertStatementNS = [[NSString alloc] initWithFormat:
								   @"insert into move \
								   (TIMESTAMP,CYCLE)\
								   values (DATETIME('now','localtime'),%d)",currentCycleID];
	
	const char* insertStatement = [insertStatementNS UTF8String];
	dbrc = sqlite3_prepare_v2(db, insertStatement, -1, &dbps, NULL);
	dbrc = sqlite3_step(dbps);

	// done with the db.  finalize the statement and close
	sqlite3_finalize(dbps);
	sqlite3_close(db);
	// End of insert into database
	NSLog(@"--- INFO - DB INSERT -> Inserted into Database! Current Cycle is %d---",currentCycleID);
}
// End of addMoveDataToDB

-(int)generateCycleID{
	// Open Database
	
	sqlite3 *db;
	int dbrc; //database RETURN CODE
	
	// create a singleton UIApplication object. Thereafter you can access this object by invoking the sharedApplicationclass method. 
	SleepDetectiveAppDelegate *appDelegate = (SleepDetectiveAppDelegate*)[UIApplication sharedApplication].delegate;
	
	const char* dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
	dbrc = sqlite3_open(dbFilePathUTF8, &db);
	if (dbrc) {
		NSLog(@"---ERROR - DB OPEN -> Couldn't Open DB! ---");
		return;
	} // End of Open DataBase
	NSLog(@"--- INFO - DB OPEN -> Open Database. ---");
		
	//
	// SELECT MAX CYCLE FROM DB
	//
	// Select all items
	
	int maxCycleId; // MAX CYCLE ID
	
	sqlite3_stmt *dbps;
	NSString *queryStmtNS = @"SELECT MAX(CYCLE) FROM move;";
	const char* queryStmt = [queryStmtNS UTF8String];
	dbrc = sqlite3_prepare_v2(db, queryStmt, -1, &dbps, NULL);
	while ((dbrc = sqlite3_step(dbps)) == SQLITE_ROW) {
		maxCycleId = sqlite3_column_int(dbps, 0);		
	}	
	// done with the db.  finalize the statement and close
	sqlite3_finalize(dbps);
	sqlite3_close(db);	
	// END OF SELECT MAX CYCLE
	return maxCycleId+1;
}

// Button Action
- (IBAction)startMonitor:(id)sender {

	imgStart = [UIImage imageNamed:@"start_btn.png"];
	imgStop = [UIImage imageNamed:@"stop_btn.png"];
	
	NSLog(@"--- INFO - SLEEP BUTTON -> Start Button Clicked ---");
	[[UIAccelerometer sharedAccelerometer] setUpdateInterval: (1/kAccelerometerFrequency) ]; // 30 fps 
	isStart = !isStart;
	if (isStart) {
		[[UIAccelerometer sharedAccelerometer] setDelegate: self];	
		NSLog(@"--- INFO - ACCELEROMETER -> START ---");	
//		[goSleepBtn setTitle:@"STOP" forState:UIControlStateNormal];
		[goSleepBtn setImage:imgStop forState:UIControlStateNormal];
	} else {
		[UIAccelerometer sharedAccelerometer].delegate = nil;
		NSLog(@"--- INFO - ACCELEROMETER -> TERMINATED ---");		
//		[goSleepBtn setTitle:@"START" forState:UIControlStateNormal];
		[goSleepBtn setImage:imgStart forState:UIControlStateNormal];
	}

}

// clock runtime
- (void)runTimer {
	// This starts the timer which fires the showActivity
	// method every 0.5 seconds
	myTicker = [NSTimer scheduledTimerWithTimeInterval: 0.5
												target: self
											  selector: @selector(showActivity)
											  userInfo: nil
											   repeats: YES];
	
}

// This method is run every 0.5 seconds by the timer created
// in the function runTimer
- (void)showActivity {
	
	NSDateFormatter *formatter =
	[[[NSDateFormatter alloc] init] autorelease];
    NSDate *date = [NSDate date];
	
    // This will produce a time that looks like "12:15:00 PM".
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
	
	// This sets the label with the updated time.
	[clockLabel setText:[formatter stringFromDate:date]];
	
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */





// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	// Here we create our deepSleepPreventer and get it to keep our iPhone from deep sleeping
	self.deepSleepPreventer = [[MMPDeepSleepPreventer alloc] init];
	[self.deepSleepPreventer startPreventSleep];
	
	currentCycleID = [self generateCycleID];
	
//	[[UIAccelerometer sharedAccelerometer] setUpdateInterval: (1/kAccelerometerFrequency) ]; // 30 fps 
//	[[UIAccelerometer sharedAccelerometer] setDelegate: self];
	
	isStart = NO;
	NSLog(@"--- INFO - SLEEP VIEW -> viewDidLoad ---");	

	// This calls the runTimer method after loading
	// SimpleClockViewController.xib
	[self runTimer];
	
}

// Implement Accelerometer Delegate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

	if (self.lastAcceleration) {
		if (!histeresisExcited && IsDeviceShaking(self.lastAcceleration, acceleration, kMaxThreshold)) {
			histeresisExcited = YES;
			
			NSLog(@"!--- [SIGNAL] - SHAKE!!! ---");
			label.text = @"!";
			[self addMoveDataToDB];
			
		} else if (histeresisExcited && !IsDeviceShaking(self.lastAcceleration, acceleration, kMinThreshold)) {
			histeresisExcited = NO;
			label.text = @"GOOD NIGHT";
		}
	}
	
	self.lastAcceleration = acceleration;	
	
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[UIAccelerometer sharedAccelerometer].delegate = nil;
	[imgStop release];
	[imgStart release];
	[label release];
	[clockLabel release];
	[myTicker release];
	[super dealloc];

}


@end
